<?php

// vim: expandtab shiftwidth=2 softtabstop=2 tabstop=2

/**
 * Group of functions to validating date
 *
 * PHP version 5
 *
 * @category  Classes
 * @package   mPack
 * @author    Marcin Sztolcman <marcin /at/ urzenia /dot/ net>
 * @copyright 2006 Marcin Sztolcman
 * @license   GPL v.2
 * @version   SVN: $Id: ns_validate.php 29 2008-01-20 23:15:20Z urzenia $
 * @link      http://m-pack.googlecode.com
 */

/**
 * Group of functions to validating date
 *
 * @category  Classes
 * @package   mPack
 * @author    Marcin Sztolcman <marcin /at/ urzenia /dot/ net>
 * @copyright 2006 Marcin Sztolcman
 * @license   GPL v.2
 * @version   SVN: $Id: ns_validate.php 29 2008-01-20 23:15:20Z urzenia $
 * @link      http://m-pack.googlecode.com
 */

abstract class Validate {
  /**
   * Validate an email address
   *
   * @param  string $s
   * @access public
   * @static
   */
  public static function email($s)
  {
    return eregi('^([a-z0-9_]|\\-|\\.)+@(((([a-z0-9_]|\\-)+\\.)+[a-z]{2,4})|localhost)$', $s);
  }

  /**
   * Validate login
   *
   * @param  string $s
   * @access public
   * @static
   */
  public static function login($s)
  {
    return preg_match('#^[a-z0-9-.,]{4,64}#i', $s);
  }

  /**
   * Validate password
   *
   * @param  string $s
   * @access public
   * @static
   */
  public static function password($s)
  {
    return preg_match('#[a-z0-9_.-]{6,256}#i', $s);
  }

  /**
   * Validate url
   *
   * @param  string $s
   * @access public
   * @static
   */
  public static function url($s)
  {
    return preg_match('#^(https?|ftps?)://[a-z0-9-]+(\.[a-z0-9-]+)*\.[a-z]{2,4}(/[^ ]*)*[a-z0-9/]?$#i', $s);
  }

  /**
   * Validate IPv4 addres
   *
   * @param string $ip
   * @param bool $validLocal if false, given IP addres cannot be local address
   * @access public
   * @static
   */
  public static function ipv4($ip, $validLocal=false)
  {
    $tmp = explode('.', $ip);
    if (4 != count($tmp)) {
      return false;
    }

    foreach ($tmp as $octet) {
      if (!is_numeric($octet)) {
        return false;
      }

      if (!Tools::inRange($octet, 0, 255)) {
        return false;
      }
    }

    if (!$validLocal) {
      //10.0.0.0 - 10.255.255.255
      if (
        $tmp[0] == 10 &&
        Tools::inRange($tmp[1], 0, 255) &&
        Tools::inRange($tmp[2], 0, 255) &&
        Tools::inRange($tmp[3], 0, 255)
      ) {
        return false;
      }

      //172.16.0.0 - 172.31.255.255
      if (
        $tmp[0] == 172 &&
        Tools::inRange($tmp[1], 16, 31) &&
        Tools::inRange($tmp[2], 0, 255) &&
        Tools::inRange($tmp[3], 0, 255)
      ) {
        return false;
      }

      //192.168.0.0 - 192.168.255.255
      if (
        $tmp[0] == 192 &&
        $tmp[1] == 168 &&
        Tools::inRange($tmp[2], 0, 255) &&
        Tools::inRange($tmp[3], 0, 255)
      ) {
        return false;
      }
    }

    return true;
  }
}

?>
